#include "list.h"

static inline void __list_add(list_obj_t *prev, list_obj_t *new, list_obj_t *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

void list_insert(list_obj_t* list, list_obj_t* node)
{
    __list_add(list, node, list->next);
}

void list_insert_tail(list_obj_t* list, list_obj_t* node)
{
    __list_add(list->prev, node, list);
}

void list_remove(list_obj_t* node)
{
    node->next->prev = node->prev;
    node->prev->next = node->next;

    list_init(node);
}

int list_isempty(const list_obj_t* list)
{
    return list->next == list;
}

unsigned int list_len(const list_obj_t* list)
{
    unsigned int len = 0;
    const list_obj_t* p = list;
    while (p->next != list)
    {
        p = p->next;
        len++;
    }

    return len;
}

void list_replace(list_obj_t *old, list_obj_t *new)
{
    new->next = old->next;
    new->next->prev = new;
    new->prev = old->prev;
    new->prev->next = new;

    old->next = old->prev = old;
}
